package com.masterclient.app.widget;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.ams.common.util.StringUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.Transformation;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.eoner.baselib.utils.notify.RxBus;
import com.eoner.baselibrary.utils.ScreenUtils;
import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselibrary.utils.UIUtils;
import com.eoner.baselibrary.utils.Utils;
import com.eoner.baselibrary.utils.ViewTransformUtil;
import com.eoner.baselibrary.widget.PermissionDialog;
import com.eoner.managerlibrary.Tools;
import com.eoner.middlelib.eventbus.EventBusManager;
import com.eoner.middlelib.eventbus.event.WXSendCancelEvent;
import com.eoner.middlelib.eventbus.event.WXSendFailedEvent;
import com.eoner.middlelib.eventbus.event.WXSendSuccessEvent;
import com.eoner.managerlibrary.user.UserDataManager;
import com.eoner.managerlibrary.weixin.WeiXinManager;
import com.masterclient.app.R;
import com.masterclient.app.modules.bridge.JsNewShareBean;
import com.masterclient.app.utils.TransformationFixedImage;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.CropCircleWithBorderTransformation;
import jp.wasabeef.glide.transformations.RoundedCornersTransformation;

/**
 * @auther hjian
 * @date 2020/6/19.
 */
public class ShareNewDialog extends Dialog  {


    @BindView(R.id.share_new_root)
    LinearLayout shareNewRoot;
    @BindView(R.id.share_h5_Ll)
    LinearLayout shareH5Ll;
    @BindView(R.id.share_h5_logo)
    ImageView shareH5Logo;
    @BindView(R.id.share_h5_life)
    ImageView shareH5Life;
    @BindView(R.id.share_h5_name)
    TextView shareH5Name;
    @BindView(R.id.share_h5_qr)
    ImageView shareH5Qr;
    @BindView(R.id.share_h5_rl)
    RelativeLayout shareH5Rl;
    @BindView(R.id.share_h5_image)
    ImageView shareH5Image;
    @BindView(R.id.share_h5_bigqr)
    ImageView shareH5Bigqr;
    @BindView(R.id.share_h5_bigll)
    LinearLayout shareH5Bigll;
    @BindView(R.id.share_h5bottom_logo)
    ImageView shareH5bottomLogo;
    @BindView(R.id.share_h5bottom_life)
    ImageView shareH5bottomLife;
    @BindView(R.id.share_h5bottom_name)
    TextView shareH5bottomName;
    @BindView(R.id.share_h5bottom_qr)
    ImageView shareH5bottomQr;
    @BindView(R.id.share_h5bottom_rl)
    RelativeLayout shareH5bottomRl;
    @BindView(R.id.share_new_image)
    ImageView shareNewImage;
    @BindView(R.id.share_new_user_avatar)
    ImageView shareNewUserAvatar;
    @BindView(R.id.share_new_user_name)
    TextView shareNewUserName;
    @BindView(R.id.share_new_user_phone)
    TextView shareNewUserPhone;
    @BindView(R.id.share_new_copy_wechat)
    TextView shareNewCopyWechat;
    @BindView(R.id.share_new_copy_phone)
    TextView shareNewCopyPhone;
    @BindView(R.id.share_new_copy_layout)
    LinearLayout shareNewCopyLayout;
    @BindView(R.id.share_new_go_wechat)
    TextView shareNewGoWechat;
    @BindView(R.id.share_new_close)
    ImageView shareNewClose;


    private RxBus rxBus;
    private Context context;
    private JsNewShareBean dataShare;

    public interface ShareCallback{
        void onShare(int status);
    }

    private ShareCallback shareCallback;



    public ShareNewDialog(@NonNull Context context,JsNewShareBean dataShare, ShareCallback shareCallback) {
        super(context);
        this.context = context;
        this.dataShare = dataShare;
        rxBus = RxBus.$();
        this.shareCallback = shareCallback;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_new_share);
        ButterKnife.bind(this);
        setCanceledOnTouchOutside(true);

        Glide.with(context).asBitmap().load(dataShare.getAlert_bg_image())
                .into(new TransformationFixedImage(shareNewImage,false));

        if ("0".equals(dataShare.getAlert_type())) {
            shareNewCopyLayout.setVisibility(View.VISIBLE);
            shareNewGoWechat.setVisibility(View.GONE);
            ViewTransformUtil.glideImageView(context, dataShare.getAlert_icon_image(), shareNewUserAvatar,
                    new Transformation[]{new CropCircleWithBorderTransformation(0, context.getResources().getColor(R.color.transparent)), new CenterCrop()},
                    R.mipmap.user_head_default_icon);
            shareNewUserName.setText("昵称："+dataShare.getAlert_show_name());
            shareNewUserPhone.setText("手机号："+dataShare.getAlert_phone());
            shareNewCopyWechat.setText(dataShare.getAlert_copy_nike_title());
            shareNewCopyPhone.setText(dataShare.getAlert_copy_phone_title());
        }else {
            shareNewCopyLayout.setVisibility(View.GONE);
            shareNewGoWechat.setVisibility(View.VISIBLE);
        }
        shareNewRoot.setVisibility(View.VISIBLE);

        shareH5Ll.setBackgroundResource(R.drawable.shape_white_14);
        shareH5Rl.setVisibility(View.GONE);
        shareH5bottomRl.setVisibility(View.VISIBLE);

        ViewTransformUtil.glideImageView(context, dataShare.getAlert_share_bg_image(), shareH5Image, new RoundedCornersTransformation(ScreenUtils.dp2px(14), 0,
                        RoundedCornersTransformation.CornerType.TOP), R.color.transparent,
                ScreenUtils.dp2px(299), ScreenUtils.dp2px(344));

        if (!TextUtils.isEmpty(UserDataManager.getInstance().getHeadImgUrl())) {
            ViewTransformUtil.glideImageView(context, UserDataManager.getInstance().getHeadImgUrl(), shareH5bottomLogo,
                    new CropCircleWithBorderTransformation(0, context.getResources().getColor(R.color.transparent)),
                    R.mipmap.user_head_default_icon, ScreenUtils.dp2px(42), ScreenUtils.dp2px(42));
        }

        shareH5bottomName.setText(((!TextUtils.isEmpty(UserDataManager.getInstance().getNickName()))
                ? UserDataManager.getInstance().getNickName() + " " : "") + dataShare.getAlert_share_title());
        shareH5bottomQr.setImageBitmap(Tools.createQRImage(dataShare.getAlert_share_url(), ScreenUtils.dp2px(52), ScreenUtils.dp2px(52)
                , BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher)));
    }


    @Override
    protected void onStart() {
        super.onStart();
        Window window = getWindow();
        WindowManager.LayoutParams windowparams = window.getAttributes();
        windowparams.width = ScreenUtils.getScreenWidth();
        windowparams.height = WindowManager.LayoutParams.MATCH_PARENT;
        window.setGravity(Gravity.CENTER);
        window.setBackgroundDrawableResource(R.color.transparent);
        window.setType(WindowManager.LayoutParams.TYPE_APPLICATION_PANEL);
        window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        window.setAttributes(windowparams);
    }



    @OnClick({R.id.share_new_copy_wechat, R.id.share_new_copy_phone,
            R.id.share_new_go_wechat, R.id.share_new_close})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.share_new_copy_wechat:
                ((ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE))
                        .setPrimaryClip(ClipData.newPlainText(null, dataShare.getAlert_show_name()));
                ToastUtil.showToast("复制成功");

                if (Tools.isAppAvilible(context,"com.tencent.mm")) {
                    shareSavePic();
                } else {
                    ToastUtil.showToast("请先安装微信客户端");
                }

                break;
            case R.id.share_new_copy_phone:
                ((ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE))
                        .setPrimaryClip(ClipData.newPlainText(null, dataShare.getAlert_phone()));
                ToastUtil.showToast("复制成功");

                if (Tools.isAppAvilible(context,"com.tencent.mm")) {
                    shareSavePic();
                } else {
                    ToastUtil.showToast("请先安装微信客户端");
                }

                break;
            case R.id.share_new_go_wechat:

                if (Tools.isAppAvilible(context,"com.tencent.mm")) {
                    shareSavePic();
                } else {
                    ToastUtil.showToast("请先安装微信客户端");
                }

                break;
            case R.id.share_new_close:
                dismiss();
                break;
        }
    }

    private RxPermissions rxPermissions;
    private void shareSavePic(){
        if (rxPermissions == null) {
            rxPermissions = new RxPermissions((Activity)context);
        }
        boolean hasPermissions = rxPermissions.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (!hasPermissions){
            new PermissionDialog(context, "开启相册权限", "保存图片需要获取保存到相册权限，请在下一个页面点击“允许”",
                    R.mipmap.icon_permission_storage, () -> requestPermissions()).show();
        }else {
            savePic();
        }
    }

    private void requestPermissions(){
        if (rxPermissions == null) {
            rxPermissions = new RxPermissions((Activity)context);
        }
        rxPermissions
                .requestEach(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(permission -> {
                    if (permission.granted) {
                        savePic();
                    } else if (permission.shouldShowRequestPermissionRationale) {
                    } else {
                        Toast.makeText(context, "保存文件权限申请失败,无法保存图片", Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void savePic(){
        Bitmap bitmap = getBitmap(shareH5Ll);
        if (bitmap == null) return;
        String path = UIUtils.getSaveImagePath(context, bitmap);
        if (WeiXinManager.checkVersionValid(context) && WeiXinManager.checkAndroidNotBelowN()) {
            path = WeiXinManager.getFileUri(context, new File(path));
        }
        if (!TextUtils.isEmpty(path)) {
            wxSharePic("he" + System.currentTimeMillis(),bitmap, path);
        } else {
            Toast.makeText(context, "保存失败", Toast.LENGTH_SHORT).show();
        }
        bitmap.recycle();
    }

    private static final String APP_ID = "wx8031a358899ba015";

    private void wxSharePic(String transaction,Bitmap bitmap, String path) {
        //初始化WXImageObject和WXMediaMessage对象
        WXImageObject imageObject;
        if (!StringUtil.isBlank(path)) {
            imageObject = new WXImageObject();
            imageObject.imagePath = path;
        } else {
            imageObject = new WXImageObject(bitmap);
        }
        WXMediaMessage msg = new WXMediaMessage();
        msg.mediaObject = imageObject;
        //设置缩略图
        Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, 200, 200, true);
        bitmap.recycle();
        msg.thumbData = Utils.bmpToByteArray(scaledBitmap,false);
        //构造一个Req
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = transaction + Long.toString(System.currentTimeMillis());
        req.message = msg;
        //表示发送给朋友圈  WXSceneTimeline  表示发送给朋友  WXSceneSession
        req.scene = SendMessageToWX.Req.WXSceneSession;
        //调用api接口发送数据到微信
        IWXAPI api = WXAPIFactory.createWXAPI(context, APP_ID);
        api.sendReq(req);
    }


    public Bitmap getBitmap(LinearLayout linearLayout){
            int h = 0;
            Bitmap bitmap;
            for (int i = 0; i < linearLayout.getChildCount(); i++) {
                h += linearLayout.getChildAt(i).getHeight();
            }
            bitmap = Bitmap.createBitmap(linearLayout.getWidth(), h,
                    Bitmap.Config.ARGB_8888);
            final Canvas canvas = new Canvas(bitmap);
            linearLayout.draw(canvas);
            return bitmap;
    }

    @Override
    public void show() {
        EventBusManager.register(this);
        super.show();
    }

    @Override
    public void dismiss() {
        EventBusManager.unRegister(this);
        super.dismiss();
    }

    /**
     * 成功
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wxSendSuccess(WXSendSuccessEvent successEvent) {

        if (shareCallback != null) {
            shareCallback.onShare(0);
        }
        Toast.makeText(context, "分享成功", Toast.LENGTH_LONG).show();
        dismiss();

    }

    /**
     * 取消
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wxSendCancel(WXSendCancelEvent cancelEvent) {
        if (shareCallback != null) {
            shareCallback.onShare(1);
        }
        Toast.makeText(context, "分享取消", Toast.LENGTH_LONG).show();
        dismiss();

    }

    /**
     * 失败
     * */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void wxSendFailed(WXSendFailedEvent failedEvent) {
        if (shareCallback != null) {
            shareCallback.onShare(2);
        }
        Toast.makeText(context, "分享失败", Toast.LENGTH_LONG).show();
        dismiss();
    }

}
